﻿using Artizan.Iot.Hub.Mqtt.Topics;
using Microsoft.Extensions.Logging;
using MQTTnet.Protocol;
using MQTTnet.Server;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.DependencyInjection;
using Volo.Abp.EventBus.Distributed;

namespace Artizan.Iot.Hub.Mqtt.Server
{
    /// <summary>
    /// TODO: 加入权限系统
    /// </summary>
    public class MqttSubscriptionService : MqttServiceBase, IMqttSubscriptionService, ITransientDependency
    {
        private readonly ILogger<MqttPublishingService> _logger;
        private readonly IDistributedEventBus _distributedEventBus;
        public MqttSubscriptionService(
            ILogger<MqttPublishingService> logger,
            IDistributedEventBus distributedEventBus)
           : base()
        {
            _logger= logger;
            _distributedEventBus = distributedEventBus;
        }
        public override void ConfigureMqttServer(MqttServer mqttServer)
        {
            base.ConfigureMqttServer(mqttServer);

            MqttServer.ClientSubscribedTopicAsync += ClientSubscribedTopicHandlerAsync;
            MqttServer.InterceptingSubscriptionAsync += InterceptingSubscriptionHandlerAsync;
            MqttServer.ClientUnsubscribedTopicAsync += ClientUnsubscribedTopicHandlerAsync;
            MqttServer.InterceptingUnsubscriptionAsync += InterceptingUnsubscriptionHandlerAsync;
        }

        /// <summary>
        /// 处理客户端订阅
        /// </summary>
        /// <param name="eventArgs"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        private Task ClientSubscribedTopicHandlerAsync(ClientSubscribedTopicEventArgs eventArgs)
        {
            _logger.LogDebug($"'{eventArgs.ClientId}' subscribed '{eventArgs.TopicFilter.Topic}'");
            return Task.CompletedTask;
        }

        /// <summary>
        /// 拦截客户端订阅
        /// </summary>
        /// <param name="eventArgs"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        private Task InterceptingSubscriptionHandlerAsync(InterceptingSubscriptionEventArgs eventArgs)
        {
            /// TODO: 使用数据库+缓存 Client 的订阅权限

            if (MqttTopicHelper.IsSystemTopic(eventArgs.TopicFilter.Topic) && eventArgs.ClientId != "Administrator")  // TODO:后续支持可配置是否可订阅指定的主题
            {
                eventArgs.Response.ReasonCode = MqttSubscribeReasonCode.ImplementationSpecificError;
            }

            if (eventArgs.TopicFilter.Topic.StartsWith(BrokerTopics.Secret.Base) && eventArgs.ClientId != "Imperator")
            {
                eventArgs.Response.ReasonCode = MqttSubscribeReasonCode.ImplementationSpecificError;
                eventArgs.CloseConnection = true;
            }

            return Task.CompletedTask;
        }

        /// <summary>
        /// 处理客户端取消订阅
        /// </summary>
        /// <param name="eventArgs "></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        private Task ClientUnsubscribedTopicHandlerAsync(ClientUnsubscribedTopicEventArgs eventArgs )
        {
            //_logger.LogDebug($"'{eventArgs.ClientId}' unsubscribed topic '{eventArgs.xxx}'");
            return Task.CompletedTask;
        }

        /// <summary>
        /// 拦截取消订阅
        /// </summary>
        /// <param name="eventArgs"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        private Task InterceptingUnsubscriptionHandlerAsync(InterceptingUnsubscriptionEventArgs eventArgs)
        {
            _logger.LogDebug($"'{eventArgs.ClientId}' unsubscribed topic '{eventArgs.Topic}'");
            return Task.CompletedTask;
        }

    }
}
